module utils {
	export class ServerManager 
	{
		private static _instance: ServerManager;
		public is_requesting:boolean;
		private request:egret.HttpRequest;
		public HostUrl:string = 'https://ptcj.dashenw.cn/cityenv/';
		public constructor() 
		{
			this.init();
		}

		public static get instance(): utils.ServerManager 
        {
            if(!this._instance) 
            {
                this._instance = new utils.ServerManager();
            }
            return this._instance;
        }

		private init():void
		{
			this.is_requesting=false;
			this.request = new egret.HttpRequest();
			this.request.responseType = egret.HttpResponseType.TEXT;
			this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        	this.request.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onPostIOError,this);
        	this.request.addEventListener(egret.ProgressEvent.PROGRESS,this.onPostProgress,this);
		}
		//请求上传积分
		public requestLogin(source:number):void
		{
			var userid = egret.getOption("userid");
			// var userid = '20_peiqi';
			if(this.is_requesting) return;
			this.is_requesting=true;


			utils.CoreData.instance.cur_source += source;
			var load_url:string = this.HostUrl+'env.php';
			this.request.addEventListener(egret.Event.COMPLETE,this.requestLoginBack,this);
			this.request.open(load_url,egret.HttpMethod.POST);
			var postData:string="type=addsource&userid="+userid+"&source="+source;
        	this.request.send(postData);
		}

		//上传积分成功返回
		private requestLoginBack(event:egret.Event):void {
			this.request.removeEventListener(egret.Event.COMPLETE,this.requestLoginBack,this);
			var resultObj=JSON.parse(this.request.response);
			if(resultObj.error.toString()=="ok"){
				utils.CoreData.instance.total_source = resultObj.arr.total;
			}else{
				utils.Toast.instance.showMsg(resultObj.msg);
			}
			this.is_requesting=false;
    	}

		//请求排行榜
		public requestRankData():void
		{
			if(this.is_requesting) return;
			var load_url:string = this.HostUrl+"rank.json?v="+egret.getTimer();
			RES.getResByUrl(load_url,this.commentInfoBack,this,RES.ResourceItem.TYPE_JSON);

		}
		//请求排行榜成功返回
		private commentInfoBack(event:any):void {
			this.request.removeEventListener(egret.Event.COMPLETE,this.commentInfoBack,this);
			this.is_requesting=false;
			for(var i=0;i<event.length;i++){
				event[i]['rank'] = i+1;
			}
			utils.CoreData.instance.rankData=event;
			pub.SignalManager.instance.dispatchSignal(pub.SignalDefin.RECEIVE_RANK_DATA);

    	}

	    private onPostIOError(event:egret.IOErrorEvent):void {
	        egret.log("post error : " + event);
			utils.Toast.instance.showMsg("请求超时!");
	    }

	    private onPostProgress(event:egret.ProgressEvent):void {
	        egret.log("post progress : " + Math.floor(100*event.bytesLoaded/event.bytesTotal) + "%");
	    }
		
	}
}